angular.module('GetStock')

.controller('GetStock.HomeCtrl', ['$scope', '$state', 'GetStockHomeService', 'User', 'Device','imanDialog', '$ionicLoading', 'Help', '$filter','$ionicModal','Socket', function($scope, $state, GetStockHomeService, User, Device, imanDialog, $ionicLoading, Help, $filter, $ionicModal,Socket) {
    
        $scope.data = {};
        var barcodeMasters = [];
        var listData = [];
        var userName,userId,departmentId,departmentName = '';
        if(User.get("Name")){
            userName = User.get("Name");
        }
        if(User.get("_id")){
            userId = User.get("_id");
        }
        if(Device.get("Department")){
            departmentId = Device.get("Department")._id;
            departmentName = Device.get("Department").Name;
        }
        
        


        var wareHouseId;//仓库id
        // var wareHouseCode;//仓库code
        var oldDatas = [];//存入获取要货看板的原始数据

        $scope.homeData = {
            transferAreaName:"", //待转区名字
            isdisabled: false, //送货按钮是否可用
            userName: User.get("Name"),
            dateNow: Date.now(),
            houses:[],//存储仓库数据
            selectHouse:''//选中的house
        };

        $scope.order = "";

        $scope.$on('$ionicView.afterEnter', function () {
            
            Socket.connect();
            init();
            
        });
        $scope.$on('$ionicView.beforeLeave', function () {
            
            Socket.disconnect();    
        });

        $ionicModal.fromTemplateUrl(u9ImHd.getFullPath('tpls/setting.html', 'GetStock'), {
            scope: $scope,
            animation: 'slide-in-right'
        }).then(function(modal) {
            $scope.modal = modal;
        });

        $scope.data.gridOptions = {
            enableRefresh: true,

            columnDefs: [{
                    col: 'ItemMasterCode',
                    name: '型号'
                }, {
                    col: 'DescSeg1',
                    name: '尺寸'
                }, {
                    col: 'DescSeg2',
                    name: '外观'
                }, {
                    col: 'RcvQty',
                    name: '现存量',
                    cls: 'getstock-column-red'
                }, {
                    col: 'TotalReceiveQty',
                    name: '到货数量'
                }, {
                    col: 'NeedDeliveryQty',
                    name: '待配送数量',
                    cls: 'getstock-column-green'
                }, {
                    col: 'DemandQty',
                    name: '要货数量',
                    cls: 'getstock-demand',
                    tpls: '<im-number-input class="col im-record-column getstock-demand" number="gridOptions.data[%d].DemandQty" ></im-number-input>'
                }, {
                    col: 'TotalDemandQty',
                    name: '累计要货'     
                }


            ],
            data: []
        };

        $scope.delivery = function(){
            // var productStreamAppID = QUALITYJUDGECONSTANTS.productStreamAppID;
            Help.loadApp('LogisticsDelivery').then(function () {
                $state.go('LogisticsDelivery', {
                    wareHouseId: wareHouseId,
                    wareHouseName: $scope.homeData.transferAreaName
                });
            }, function () {
                imanDialog.toastBottom('进入物流配送应用失败，请确认是否已正确安装然后重试。');
            });
        };

        $scope.doRefresh = function(operate, item) {
            imanDialog.showLoading();
            GetStockHomeService.queryGetStockData(wareHouseId,departmentId).then(function(data){
                   imanDialog.hideLoading();
                   initKanbanData(data);
                   
                },function(error){
                   // imanDialog.toastBottom("获取要货看板数据失败，"+error);
                   imanDialog.hideLoading();
                });
            $scope.$broadcast('scroll.refreshComplete');
        };

        $scope.search = function(query) {
            if (query === "") {
                $scope.data.gridOptions.data = listData;
            }
            if (query !== "") {
                var nPosDescSeg1;
                var nPosDescSeg2;
                var nPosItem;
                $scope.data.gridOptions.data = [];

                for (var i in listData) {
                    var DescSeg1 = listData[i].DescSeg1;
                    var DescSeg2 = listData[i].DescSeg2;
                    var itemMasterCode = listData[i].ItemMasterCode;
                    nPosDescSeg1 = find(query, DescSeg1);
                    nPosDescSeg2 = find(query, DescSeg2);
                    nPosItem = find(query, itemMasterCode);
                    //nPos=sTxt.indexOf(sFind);   
                    if (nPosDescSeg1 >= 0 || nPosDescSeg2 >= 0 || nPosItem >= 0) {

                        $scope.data.gridOptions.data.push(listData[i]);
                    }
                }
                if ($scope.data.gridOptions.data.length === 0) {
                    imanDialog.toastBottom('未找到相关信息');
                }
            }

        };

        
        
        $scope.gethouses = function() {

            imanDialog.showLoading();
            GetStockHomeService.getAllWareHouse().then(function(data){
                imanDialog.hideLoading();
                if(data){
                    $scope.homeData.houses = data;
                    $scope.modal.show().then(function () {
                                
                    });
                }
                
            },function(error){
                // imanDialog.toastBottom(error+"获取要货看板数据失败");
                imanDialog.hideLoading();
            });

        };

        $scope.initData = function(wareHouse) {
             if(wareHouseId){
                Socket.off(wareHouseId.toString(), onSocket);
             }
             initData(wareHouse);
        };
        

        $scope.submitData = function() {
            imanDialog.showLoading();
            var submitData = [];
            for (var i = 0; i < listData.length; i++) {
                // var oldData = oldDatas[i];
                var newData = listData[i];
                if(newData.KanbanId){
                    submitData.push({
                        DemandQty: newData.DemandQty,
                        TotalDemandQty: newData.TotalDemandQty,
                        KanbanId:newData.KanbanId
                    });
                }
                else{
                    if(newData.DemandQty>0){
                        submitData.push({
                            ItemMaster: newData.ItemMaster,
                            DescSeg1:newData.DescSeg1,
                            DescSeg2:newData.DescSeg2, 
                            WareHouse: wareHouseId,
                            DemandQty: newData.DemandQty,
                            TotalDemandQty: 0,
                            TotalStockQty: 0,
                            TotalReceiveQty: 0,
                            KanbanId:null,
                            DemandDepartment: departmentId
                        });
                    }
                    
                }
                

            }

            GetStockHomeService.submitDemandQty(userId,submitData).then(function(data){
               if(data){
                  imanDialog.toastBottom("提交成功"); 
               } 
               else{
                  imanDialog.toastBottom("提交失败");
               }
               GetStockHomeService.queryGetStockData(wareHouseId, departmentId).then(function(data){
                   imanDialog.hideLoading();
                   initKanbanData(data);
                },function(error){
                   // imanDialog.toastBottom("获取要货看板数据失败，"+error);
                   imanDialog.hideLoading();
                });
               
            },function(error){
               imanDialog.hideLoading();
            });
        };
    

    
    
    function init(){
        var wareHouse = angular.fromJson(window.localStorage.getItem("wareHouse"));
        if(wareHouse){
            
            initData(wareHouse);
        }
    }
    

    function initKanbanData(data){
       // var updateDatas = [];
       var updateDatasTotalDemandQty0 = [];//累计要货为0的
       var updateDatasTotalDemandQty = []; //累计要货不为0的
       var addDatas = [];

       if(data.length>0){
          for (var i = 0; i < data.length; i++) {
             
             if(data[i].KanbanId){
                    if(data[i].TotalDemandQty===0){
                        updateDatasTotalDemandQty0.push(data[i]);
                    }
                    else{
                        updateDatasTotalDemandQty.push(data[i]);
                    }       
             }
             else{
                addDatas.push(data[i]);
             } 
          }
       }

       data = updateDatasTotalDemandQty.concat(updateDatasTotalDemandQty0).concat(addDatas);
       // $scope.data.gridOptions.data = $filter('orderBy')(data, 'NeedDeliveryQty', true);
       $scope.data.gridOptions.data = data;
       listData = $scope.data.gridOptions.data;
        
    }

    function initData(wareHouse){
        $scope.homeData.selectHouse = wareHouse.Name;
        wareHouseId = wareHouse._id;
        
        Socket.on(wareHouseId.toString(), onSocket);
        
        window.localStorage.setItem("wareHouse", angular.toJson(wareHouse));
        imanDialog.showLoading();
        GetStockHomeService.queryGetStockData(wareHouse._id,departmentId).then(function(data){
           imanDialog.hideLoading();
           $scope.modal.hide();
           initKanbanData(data);
           
        },function(error){
           $scope.modal.hide();
           // imanDialog.toastBottom("获取要货看板数据失败，"+error);
           $scope.data.gridOptions.data = [];
           imanDialog.hideLoading();
        });
    }

    function onSocket () {
        // imanDialog.toastBottom("on");
        imanDialog.showLoading();
        GetStockHomeService.queryGetStockData(wareHouseId,departmentId).then(function(data){
           imanDialog.hideLoading();
           initKanbanData(data);
           
        },function(error){
           // imanDialog.toastBottom("获取要货看板数据失败，"+error);
           $scope.data.gridOptions.data = [];
           imanDialog.hideLoading();
        });
    }
    

    function find(sFind, sObj) {
        var nSize = sFind.length;
        var nLen = sObj.length;
        var sCompare;

        if (nSize <= nLen) {
            for (var i = 0; i <= nLen - nSize + 1; i++) {
                sCompare = sObj.substring(i, i + nSize);
                if (sCompare === sFind) {
                    return i;
                }
            }
        }
        return -1;
    }

    
}]);